﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>

    public partial class YCAFDPLAN : DocumentBase
    {

        Queue<DataSet> JobQueue;
        bool IsSupplierLoded = false;
        YCAEK03DOC m_Prn;
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        INTEXDBC INTEXDBC;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetTmp
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetTmp");
            }
        }
        BackgroundWorker bgWorker;
        public bool IsPlanMode
        {
            get
            {
                if (ChkPlanMode.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
        }
        public bool IsOverride
        {
            get
            {
                if (ChkOverride.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
        }
        public bool IsShowPlanned
        {
            get
            {
                if (ChkPlanned.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
        }
        public bool IsMatMode
        {
            get
            {
                if (ChkMatMode.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkMatMode.IsChecked = true;
                }
                else
                {
                    ChkMatMode.IsChecked = false;
                }
            }
        }
        public bool IsAutoAllocation
        {
            get
            {
                if (AutoAllocation.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    AutoAllocation.IsChecked = true;
                }
                else
                {
                    AutoAllocation.IsChecked = false;
                }
            }
        }
        public bool IsAutoSplit
        {
            get
            {
                if (AutoSplit.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    AutoSplit.IsChecked = true;
                }
                else
                {
                    AutoSplit.IsChecked = false;
                }
            }
        }

        DataRow LastRow = null;
        bool IsRunning = false;
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        string Today
        {
            get
            {
                return System.DateTime.Now.Year.ToString()
                    + m_Data.Right("00" + System.DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + System.DateTime.Now.Day.ToString(), 2);
            }
        }
        string JobType = "AUTOEK";
        YCAFDPLANData m_Data;
        string ART
        {
            get
            {
                return m_Data.Left(txtMAT.Text.ToString().PadRight(20), 20);
            }
            set
            {
                txtMAT.Text = value;
            }
        }
        string FART
        {
            get
            {
                return m_Data.Left(txtFS03.Text.ToString().PadRight(20), 20);
            }
            set
            {
                txtFS03.Text = value;
            }
        }
        string KRS
        {
            get
            {
                return m_Data.Left(txtKRS.Text.ToString() + "                      ", 3);
            }
            set
            {
                txtKRS.Text = value;
            }
        }
        string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtLFD.Text.ToString().Trim(), 6);
            }
            set
            {
                txtLFD.Text = value;
            }
        }
        SETINTEXDB.ICC_EKPOSDataTable tpEKPOS = new SETINTEXDB.ICC_EKPOSDataTable();
        public string pSType
        {
            get
            {
                return m_Data.Left(SType.Text + "  ", 1);
            }
            set
            {
                SType.Text = value;
            }
        }
        public string pSKRS
        {
            get
            {
                return m_Data.Left(SKRS.Text + "   ", 2);
            }
            set
            {
                SKRS.Text = value;
            }
        }
        public string pSLFD
        {
            get
            {
                return m_Data.Left(SLFD.Text + "       ", 6);
            }
            set
            {
                SLFD.Text = value;
            }
        }
        public string pSPOS
        {
            get
            {
                return m_Data.Left(SPOS.Text + "   ", 3);
            }
            set
            {
                SPOS.Text = value;
            }
        }
        public string pSAID
        {
            get
            {
                return m_Data.Left(SAID.Text + "   ", 3);
            }
            set
            {
                SAID.Text = value;
            }
        }
        public double pSQTY
        {
            get
            {
                if (SQTY.Text.ToString() == "")
                    return 0;
                return System.Convert.ToDouble(SQTY.Text);
            }
            set
            {
                SQTY.Text = value.ToString();
            }
        }
        #region=====vwITXXDECK=======
        CollectionViewSource vwITXXDECK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwITXXDECK");
            }
        }
        DataRow dwITXXDECK
        {
            get
            {
                if (vwITXXDECK.View == null)
                    return null;
                if ((DataRowView)vwITXXDECK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwITXXDECK.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwNCXDECK=======
        CollectionViewSource vwNCXDECK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwNCXDECK");
            }
        }
        DataRow dwNCXDECK
        {
            get
            {
                if (vwNCXDECK.View == null)
                    return null;
                if ((DataRowView)vwNCXDECK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwNCXDECK.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwXDECK=======
        CollectionViewSource vwXDECK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwXDECK");
            }
        }
        DataRow dwXDECK
        {
            get
            {
                if (vwXDECK.View == null)
                    return null;
                if (vwXDECK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwXDECK.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwITXABPOS=======
        CollectionViewSource vwITXABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwITXABPOS");
            }
        }
        DataRow dwITXABPOS
        {
            get
            {
                if (vwITXABPOS.View == null)
                    return null;
                if ((DataRowView)vwITXABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwITXABPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwITXEKPOS=======
        CollectionViewSource vwITXEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwITXEKPOS");
            }
        }
        DataRow dwITXEKPOS
        {
            get
            {
                if (vwITXEKPOS.View == null)
                    return null;
                if ((DataRowView)vwITXEKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwITXEKPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwITXSTOCK=======
        CollectionViewSource vwITXSTOCK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwITXSTOCK");
            }
        }
        DataRow dwITXSTOCK
        {
            get
            {
                if (vwITXSTOCK.View == null)
                    return null;
                if ((DataRowView)vwITXSTOCK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwITXSTOCK.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwITXAB15=======
        CollectionViewSource vwITXAB15
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwITXAB15");
            }
        }
        DataRow dwITXAB15
        {
            get
            {
                if (vwITXAB15.View == null)
                    return null;
                if ((DataRowView)vwITXAB15.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwITXAB15.View.CurrentItem).Row;
            }
        }
        #endregion
        string EKPBEKZ
        {
            get
            {
                if (ChkEKPBEKZ.IsChecked == true)
                {
                    return "N";
                }
                return " ";
            }
        }
        #region=====vwTMPEKPOS=======
        CollectionViewSource vwTMPEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTMPEKPOS");
            }
        }
        DataRow dwTMPEKPOS
        {
            get
            {
                if (vwTMPEKPOS.View == null)
                    return null;
                if ((DataRowView)vwTMPEKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwTMPEKPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwLIEFDAT=======
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        #endregion
        BindingListCollectionView cvXDECK
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgXDECK.ItemsSource);
            }
        }
        BackgroundWorker bgWoker;
        public YCAFDPLAN()
        {
            InitializeComponent();
            this.Name = "高级辅料采购";
            JobQueue = new Queue<DataSet>();
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_Data = new YCAFDPLANData(OracleDB, proxy);
                    INTEXDBC = new INTEXDBC(OracleDB, proxy);
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    cmbKRS.Text = "FP";
                    SetEnv.Merge(m_Data.SetUpUI());
                    DataTable tb = SetData.ICC_ABAUFM.Clone();
                    tb.TableName = "NC_ICC_ABAUFM";
                    SetData.Merge(tb);
                }
                IsLoaded = false;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        #region======common========
        private void Windows_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsLoaded)
                return;
            IsLoaded = true;
            vwITXABPOS.View.CurrentChanged += vwITXABPOS_CurrentChanged;
            vwXDECK.View.CurrentChanged += vwXDECK_CurrentChanged;
            vwITXSTOCK.View.CurrentChanged += vwITXSTOCK_CurrentChanged;
            vwITXAB15.View.CurrentChanged += vwITXAB15_CurrentChanged;
            vwTMPEKPOS.View.CurrentChanged += vwTMPEKPOS_CurrentChanged;
            vwITXEKPOS.View.CurrentChanged += vwTMPEKPOS_CurrentChanged;
            vwNCXDECK.View.CurrentChanged += vwNCXDECK_CurrentChanged;
            vwITXXDECK.View.CurrentChanged += vwITXXDECK_CurrentChanged;
            vwITXEKPOS.View.CurrentChanged += vwITXEKPOS_CurrentChanged;
            if (!tpEKPOS.Columns.Contains("ABPART"))
            {
                tpEKPOS.Columns.Add("ABPART", typeof(string));
            }
            if (!tpEKPOS.Columns.Contains("EKPLSARTBEZ"))
            {
                tpEKPOS.Columns.Add("EKPLSARTBEZ", typeof(string));
            }
            bgWoker = new BackgroundWorker();
            bgWoker.DoWork += bgWoker_DoWork;
            bgWoker.RunWorkerCompleted += bgWoker_RunWorkerCompleted;
            bgWoker.RunWorkerAsync();
        }
        void bgWoker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            EventDispatcher.Instance.RaiseStatus("更新完成", StatusEventType.StopProgress);
        }
        void bgWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            EventDispatcher.Instance.RaiseStatus("开始更新", StatusEventType.StartProgress);
            m_Data.Refresh();
        }
        void vwITXXDECK_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (dwITXXDECK == null)
                    return;
                Set4ITX.ABPOS.Clear();
                Set4ITX.ICC_ABAUFM.Clear();
                DataRow row = dwITXXDECK;
                string krs = row["ABAVKAUFKRS"].ToString();
                string lfd = row["ABAVKAUFLFD"].ToString();
                string pos = row["ABAVKAUFPOS"].ToString();
                string ABAID = row["ABAID"].ToString();

                var query = from rx in SetData.ABPOS.AsEnumerable()
                            where rx["ABPAUFKRS"].ToString() == krs
                            && rx["ABPAUFLFD"].ToString() == lfd
                            select rx;
                Set4ITX.ABPOS.Clear();
                if (query.Count() > 0)
                {
                    Set4ITX.ABPOS.Merge(query.CopyToDataTable());
                }
                if (vwITXABPOS.View != null)
                {
                    vwITXABPOS.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        void vwNCXDECK_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                Set4ITX.ABPOS.Clear();
                Set4ITX.ICC_ABAUFM.Clear();
                if (dwNCXDECK == null)
                    return;
                DataRow row = dwNCXDECK;
                string krs = row["ABAVKAUFKRS"].ToString();
                string lfd = row["ABAVKAUFLFD"].ToString();
                string pos = row["ABAVKAUFPOS"].ToString();
                string ABAID = row["ABAID"].ToString();

                var query = from rx in SetData.ABPOS.AsEnumerable()
                            where rx["ABPAUFKRS"].ToString() == krs
                            && rx["ABPAUFLFD"].ToString() == lfd
                            select rx;
                Set4ITX.ABPOS.Clear();
                Set4ITX.ABPOS.Merge(query.CopyToDataTable());
                if (vwITXABPOS.View != null)
                {
                    vwITXABPOS.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        void vwTMPEKPOS_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                DataRow dwInput = null;

                dwInput = dwTMPEKPOS;
                if (dwInput == null)
                    dwInput = dwITXEKPOS;
                if (dwInput == null)
                    return;
                if (LastRow == dwInput)
                    return;
                LastRow = dwInput;
                btnPurchase.IsEnabled = true;
                txtMessage.Text = "";
                return;
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    DataRow dwData = SetData.ICC_XDECK.NewRow();
                    dwData["MANDANT"] = "00";
                    dwData["ART"] = dwInput["EKPART"];
                    dwData["VAR"] = dwInput["EKPVAR"];
                    dwData["COLOR"] = dwInput["EKPFARBE"];
                    dwData["ASIZE"] = dwInput["EKPGROE"];
                    dwData["CREF"] = dwInput["EKPLSGRPBEZ"];
                    dwData["ABPART"] = dwInput["ABPART"];
                    //LOADXDECK(dwData, dwInput, IsShowPlanned, txtSection.Text, false);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        void vwITXAB15_CurrentChanged(object sender, EventArgs e)
        {
            if (dwITXAB15 == null)
                return;
            txtMAT.Text = dwITXAB15["ABAART"].ToString().Trim();
            return;
            if (LastRow == dwITXAB15)
                return;
            LastRow = dwITXAB15;
            var query = from row in SetData.ICC_XDECK.AsEnumerable()
                        where row["ART"].ToString().Trim() == dwITXAB15["ABAART"].ToString().Trim()
                        && row["VAR"].ToString().Trim() == dwITXAB15["ABAVAR"].ToString().Trim()
                        && row["COLOR"].ToString().Trim() == dwITXAB15["ABAFARBE"].ToString().Trim()
                        && row["ASIZE"].ToString().Trim() == dwITXAB15["ABAGROE"].ToString().Trim()
                        select row;
            int index = -1;

            foreach (DataRow row in SetData.ICC_XDECK.Rows)
            {
                index++;
                if (row["ART"].ToString().Trim() == dwITXAB15["ABAART"].ToString().Trim()
                      && row["VAR"].ToString().Trim() == dwITXAB15["ABAVAR"].ToString().Trim()
                      && row["COLOR"].ToString().Trim() == dwITXAB15["ABAFARBE"].ToString().Trim()
                      && row["ASIZE"].ToString().Trim() == dwITXAB15["ABAGROE"].ToString().Trim()
                    )
                {
                    vwXDECK.View.MoveCurrentToPosition(index);
                    break;
                }
            }
        }
        void vwITXEKPOS_CurrentChanged(object sender, EventArgs e)
        {
            if (!IsMatMode)
                return;
            if (dwITXEKPOS == null)
                return;
            /*if (LastRow == dwITXEKPOS)
                return;
            LastRow = dwITXEKPOS;*/
            try
            {
                pSType = "P";
                pSKRS = dwITXEKPOS["EKPAUFKRS"].ToString();
                pSLFD = dwITXEKPOS["EKPAUFLFD"].ToString();
                pSPOS = dwITXEKPOS["EKPAUFPOS"].ToString();
                pSAID = dwITXEKPOS["EKPAID"].ToString();
                pSQTY = System.Convert.ToDouble(dwITXEKPOS["EKPQTYFREE"].ToString());
                vwITXXDECK.View.MoveCurrentTo(-1);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        void vwITXABPOS_CurrentChanged(object sender, EventArgs e)
        {

            DataSet SResult = new DataSet();
            if (dwITXABPOS == null)
                return;
            if (LastRow == dwITXABPOS)
                return;
            LastRow = dwITXABPOS;
            using (new LongOperation(this, "读取符合条件的记录"))
            {
                SResult = m_Data.LoadABPOSData(dwITXABPOS);
            }
            Set4ITX.ICC_ABAUFM.Clear();
            Set4ITX.ICC_ABAUFM.Merge(SResult.Tables[0]);
        }
        void vwITXSTOCK_CurrentChanged(object sender, EventArgs e)
        {
            if (!IsMatMode)
                return;
            if (dwITXSTOCK == null)
                return;
            if (LastRow == dwXDECK)
                return;
            LastRow = dwITXSTOCK;
            pSType = "B";
            pSKRS = dwITXSTOCK["LO"].ToString();
            pSLFD = dwITXSTOCK["LB"].ToString();
            pSPOS = "000";
            pSAID = dwITXSTOCK["BAID"].ToString();
            pSQTY = System.Convert.ToDouble(dwITXSTOCK["QTYFREE"].ToString());
            vwITXXDECK.View.MoveCurrentTo(-1);
        }
        void vwXDECK_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (!IsPlanMode)
                    return;
                if (dwXDECK == null)
                    return;
                txtMAT.Text = dwXDECK["ART"].ToString().Trim();
                txtSELLER.Text = dwXDECK["SELLER"].ToString().Trim();
                txtFART.Text = dwXDECK["ABPART"].ToString().Trim();
                txtColorRef.Text = dwXDECK["CREF"].ToString().Trim(); 

                LastRow = dwXDECK;
                btnPurchase.IsEnabled = true;
                txtMessage.Text = ""; 
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    LOADXDECK(dwXDECK, dwXDECK, IsShowPlanned, txtSection.Text, true);
                    string filter = "ABPSPGRD>'89'";
                    DataRow[] rows = SetData.ABPOS.Select(filter);
                    if (rows.Length > 0)
                    {
                        //btnPurchase.IsEnabled = false;
                        txtMessage.Text = "主面料尚未通过审核。";
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            {

                EventDispatcher.Instance.RaiseStatus(txtLogIn.Text, StatusEventType.UserLogIn);
            }
        }
        public override void OnWorkflowIDChange(string wfid)
        {
            base.OnWorkflowIDChange(wfid);
            try
            {
                dwWFEvent = null;
                DataSet SResult = m_Data.INTEXDBC.QueryICC_WFEVENTS(wfid, 1);
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    dwWFEvent = row;
                }
                if (dwWFEvent == null)
                    return;
                string events = dwWFEvent["WFEVENTS"].ToString().Trim();
                switch (events)
                {
                    case "A001021"://主面料已经审核，辅料可以采购
                        FART = dwWFEvent["ARTICLE"].ToString();
                        KRS = dwWFEvent["KRS"].ToString();
                        LFD = dwWFEvent["LFD"].ToString();                        
                        btnQuery_Click(null, null);
                        if (this.vwITXAB15.View != null)
                            vwITXAB15.View.MoveCurrentToPosition(0);
                        break; 
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult = new DataSet();
            try
            {
                bgWoker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                SetData.Clear();
                SetData.Merge(SResult);
            }
        }
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult = new DataSet();
            try
            {
                cvXDECK.CustomFilter = null;
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    DataRow dwData = SetData.ICC_XDECK.NewRow();
                    dwData["ART"] = ART;
                    dwData["FART"] = FART;
                    dwData["KRS"] = KRS;
                    dwData["LFD"] = LFD;
                    SResult = m_Data.LoadGXDECKData(dwData, txtSection.Text);
                    //txtMAT.Text = "";
                    SetData.Clear();
                    SetData.Merge(SResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                SetData.Clear();
                SetData.Merge(SResult);
            }
        }
        private void btnDiscard_Click(object sender, RoutedEventArgs e)
        {
            tpEKPOS.Clear();
            SetTmp.Clear();
            Set4ITX.ICC_EKPOS.Clear();
        }
        private void ChkMatMode_Checked(object sender, RoutedEventArgs e)
        {
            if (IsMatMode)
            {
                zonePlan.IsExpanded = false;
                //zoneSource.IsExpanded = true;
            }
            else
            {
                zonePlan.IsExpanded = true;
                //zoneSource.IsExpanded = true;
            }
        }

        private void btnRefreshPurchase_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnPurchase.IsEnabled = false;
                btnRefreshPurchase.IsEnabled = false;
                if (!IsSupplierLoded)
                {
                    SetData.Merge(m_Data.LoadSupplier());
                    IsSupplierLoded = true;
                }
                if (dlgTempEK.IsEnabled)
                {
                    dlgTempEK.IsEnabled = false;
                    dlgTempEK.Visibility = Visibility.Hidden;
                }
                if (!imgneworder.IsEnabled)
                {
                    imgneworder.IsEnabled = true;
                    imgneworder.Visibility = Visibility.Visible;
                }
                zonePlan.IsExpanded = false;
                AUTOEK();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnITXPurchase_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool IsSuccess = true;
                string msg = "";
                foreach (DataRow rw in Set4ITX.Tables["ICC_EKPOS"].Rows)
                {
                    rw["EKPLDAT"] = Helper.GeStrDate(rw["EKPLTERM"].ToString());
                }
                m_Data.CheckData(Set4ITX, ref IsSuccess, ref msg);
                if (!IsSuccess)
                {
                    MessageBox.Show(msg);
                    return;
                }
                if (imgneworder.IsEnabled)
                {
                    imgneworder.IsEnabled = false;
                    imgneworder.Visibility = Visibility.Hidden;
                }
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    m_Data.ITXPurchase(Set4ITX, txtSection.Text, IsAutoAllocation, IsAutoSplit);
                    if (vwITXEKPOS.View != null)
                    {
                        vwITXEKPOS.View.MoveCurrentTo(-1);
                    }
                }
            }
            catch (Exception ex)
            {

                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                btnRefreshPurchase.IsEnabled = true;
            }
        }

        private void dlgITXDECK_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (dwITXXDECK == null)
                return;
            decimal cqty = 0, fqty = 0;
            string krs = dwITXXDECK["ABAAUFKRS"].ToString();
            string lfd = dwITXXDECK["ABAAUFLFD"].ToString();
            string pos = dwITXXDECK["ABAAUFPOS"].ToString();
            if (lfd.Trim() == "")
                return;
            if (pSType == "P")
            {
                var qEKP = from DataRow rx in Set4ITX.ICC_EKPOS.AsEnumerable()
                           where rx["EKPAUFKRS"].ToString() == krs
                           && rx["EKPAUFLFD"].ToString() == lfd
                           && rx["EKPAUFPOS"].ToString() == pos
                           select rx;
                foreach (DataRow rx in qEKP)
                {
                    DataRow EKP = rx;
                    cqty = System.Convert.ToDecimal(EKP["EKPQTYFREE"].ToString());
                    fqty = System.Math.Round(System.Convert.ToDecimal(dwITXXDECK["ABAQTYRESERVE"].ToString()), 0);
                    EKP["EKPQTYFREE"] = System.Math.Round(cqty + fqty, 2);
                    decimal EKPME1 = System.Convert.ToDecimal(EKP["EKPME1"].ToString());
                    EKP["EKPQTYLOCKED"] = EKPME1 - (cqty + fqty);
                    break;
                }
            }
            if (pSType == "B")
            {
                cqty = System.Convert.ToDecimal(dwITXSTOCK["QTYFREE"].ToString());
                fqty = System.Convert.ToDecimal(dwITXXDECK["ABAQTYALLOCATE"].ToString());
                dwITXEKPOS["QTYFREE"] = cqty + fqty;
                decimal QTY = System.Convert.ToDecimal(dwITXSTOCK["QTY"].ToString());
                dwITXSTOCK["QTYLOCKED"] = QTY - (cqty + fqty);
            }
            dwITXXDECK["ABAAUFTYP"] = "N";
            dwITXXDECK["ABAAUFKRS"] = "  ";
            dwITXXDECK["ABAAUFLFD"] = "      ";
            dwITXXDECK["ABAAUFPOS"] = "   ";
            dwITXXDECK["ABAQTYALLOCATE"] = 0;
            dwITXXDECK["ABAQTYRESERVE"] = 0;
            INTEXDBC.UpdateICC_ABAUFM(dwITXXDECK, 1);//这里是满足需求的关系，若是部分满足，则拆分数量 

        }
        private void btnDelAllocation_Click(object sender, RoutedEventArgs e)
        {
            if (txtRDel.Text.Trim() != "Y")
                MessageBox.Show("请先把标志改为Y");
            string orders=m_Data.DeleteReservation(SetData);
            txtMessage.Text = orders + "已经删除";
        }
        private void btnRefreshAllocation_Click(object sender, RoutedEventArgs e)
        {
            INTEXDBC.UpdateICC_ABAUFM(dwITXXDECK, 1);//这里是满足需求的关系，若是部分满足，则拆分数量
        }
        private void btnPurchase_Click(object sender, RoutedEventArgs e)
        {
            DataTable temp = new DataTable();
            try
            {
                if (IsRunning)
                    return;
                if (cmbKRS.Text.ToString().Trim() == "")
                {
                    MessageBox.Show("请确定前缀");
                    return;
                }
                double prodplanrate = Convert.ToDouble(txtPlanRate.Text);
                double wastageek = Convert.ToDouble(txtWastageEK.Text);
                if (prodplanrate == 0
                       || wastageek == 0)
                {
                    //MessageBox.Show("请设置加成和采购损耗!");
                    //return;
                }
                if (!dlgTempEK.IsEnabled)
                {
                    dlgTempEK.IsEnabled = true;
                    dlgTempEK.Visibility = Visibility.Visible;
                    IsMatMode = false;
                }
                temp = SetData.ICC_XDECK.Clone();
               
                /*dwXDECK["PLANRATE"] = prodplanrate;
                dwXDECK["WASTAGEEK"] = wastageek;
                txtTmpEKME1.Text = Math.Round(Convert.ToDouble(dwXDECK["REQ"].ToString()) * (1 + prodplanrate * 0.01) * (1 + wastageek * 0.01), 2).ToString();*/
                foreach (DataRowView vw in dlgXDECK.SelectedItems)
                {
                    string ART = vw.Row["ART"].ToString();
                    string VAR = vw.Row["VAR"].ToString();
                    string FARBE = vw.Row["COLOR"].ToString();
                    string SIZE = vw.Row["ASIZE"].ToString();
                    string CREF = vw.Row["CREF"].ToString();
                    string SELLER = vw.Row["SELLER"].ToString();
                    string ABPART = vw.Row["ABPART"].ToString();
                    string ABPSPGRD = vw.Row["ABPSPGRD"].ToString();
                    string ABAVKAUFKRS = vw.Row["ABAVKAUFKRS"].ToString();
                    string ABAVKAUFLFD = vw.Row["ABAVKAUFLFD"].ToString();
                    if (ABPSPGRD.Trim() == "")
                        ABPSPGRD = "0";
                    //if (Convert.ToDecimal(ABPSPGRD) >89)
                       // continue;                        
                    var emp = (from DataRow rw in SetData.ICC_XDECK.AsEnumerable()
                               where rw["ART"].ToString() == ART
                               && rw["VAR"].ToString() == VAR
                               && rw["COLOR"].ToString() == FARBE
                               && rw["ASIZE"].ToString() == SIZE
                               && rw["CREF"].ToString() == CREF
                               && rw["SELLER"].ToString() == SELLER
                               && rw["ABPART"].ToString() == ABPART
                               && rw["ABAVKAUFKRS"].ToString() == ABAVKAUFKRS
                               && rw["ABAVKAUFLFD"].ToString() == ABAVKAUFLFD
                               select rw).Distinct().First();
                    DataRow rx = temp.NewRow();
                    rx.ItemArray = emp.ItemArray;
                    temp.Rows.Add(rx);
                    //temp.Merge(emp.CopyToDataTable());
                }
                string processed = "";
                foreach (DataRow vw in temp.Rows)
                {
                    string ART = vw["ART"].ToString();
                    string VAR = vw["VAR"].ToString();
                    string FARBE = vw["COLOR"].ToString();
                    string SIZE = vw["ASIZE"].ToString();
                    string CREF = vw["CREF"].ToString();
                    string ABAVKAUFKRS = vw["ABAVKAUFKRS"].ToString();
                    string ABAVKAUFLFD = vw["ABAVKAUFLFD"].ToString();
                    string key = ART + VAR + FARBE + SIZE + CREF;
                    if (processed.Contains(key + ";"))
                        continue;
                    processed += key + ";";
                    DataRow rek = tpEKPOS.NewICC_EKPOSRow();
                    //byte[] bytes = Encoding.ASCII.GetBytes(m_Data.Left(vw["MDMAT"].ToString() + "                        ", 20));
                    rek["EKPART"] = m_Data.Left(vw["ART"].ToString() + "                        ", 20);
                    //bytes = Encoding.ASCII.GetBytes(m_Data.Left(vw["MDVAR"].ToString() + "     ", 3));
                    rek["EKPVAR"] = m_Data.Left(vw["VAR"].ToString() + "     ", 3);
                    //bytes = Encoding.ASCII.GetBytes(m_Data.Left("               ", 10));
                    rek["EKPFARBE"] = m_Data.Left(vw["COLOR"].ToString() + "     ", 10);
                    rek["EKPDESS"] = m_Data.Left("               ", 10);
                    rek["EKPCOL"] = m_Data.Left("               ", 10);
                    rek["EKPBESCH"] = m_Data.Left("               ", 10);
                    rek["EKPZUSTAND"] = m_Data.Left("               ", 4);
                    rek["EKPGROE"] = m_Data.Left(vw["ASIZE"].ToString() + "     ", 7);
                    rek["EKPNEUD"] = Today;
                    rek["EKPNEUB"] = m_Data.Left(txtUserID.Text.ToString() + "      ", 8);
                    rek["EKPAUFKRS"] = m_Data.Left(cmbKRS.Text.ToString().Trim() + "   ", 2);
                    rek["EKPME1"] = vw["REQ"].ToString();// System.Math.Round(System.Convert.ToDecimal(vw["MDMENGE"].ToString()) * 100, 0);
                    if (vw["UM"].ToString().Trim() == "")
                    {
                        MessageBox.Show("请通知维护人员确定该产品的单位:" + ART);
                        vw["UM"] = "PCS";
                    }
                    rek["EKPMEEH"] = vw["UM"];
                    rek["EKPPREH"] = vw["UM"];

                    rek["EKPMEEHGRP"] = 1;
                    rek["EKPPREHGRP"] = 1;
                    rek["EKPMEEHFKT"] = "000001000000";
                    rek["EKPLSGRPBEZ"] = m_Data.Left(CREF, 20);
                    rek["EKKBUCHKRS"] = Helpers.Helper.Left(cmbEKType.Text + "   ", 3);
                    rek["EKPSMENGE"] = "0";
                    rek["EKPLIEFNR"] = "00000000";
                    rek["ABPART"] = vw["ABPART"];
                    rek["EKPFAUFKRS"] = vw["ABAVKAUFKRS"];
                    rek["EKPFAUFLFD"] = vw["ABAVKAUFLFD"];
                    
                    //rek["EKPLSARTBEZ"] = Helpers.Helper.Left(vw["EXART"].ToString() + "-" + vw["EXCOLOR"].ToString() + "                                                                                                 ", 40);
                    rek["EKPLSARTBEZ"] = Helpers.Helper.Left(vw["ART"].ToString().Trim() + "-" + vw["COLOR"].ToString() + "                                                                                                 ", 40);
                    /*
             按照标准BOM推算出的重量是100kg，采购损耗是3%，采购加成是5%
（100*1.05）=加成后的重量*.97是有效的重量
EKPEFARBE=（100*1.05）*0.97
EKPME1=（100*1.05）
EKPEART=0;0.97;*/
                    /*double prodplanrate = Convert.ToDouble(vw["PLANRATE"].ToString());
                    double wastageek = Convert.ToDouble(vw["WASTAGEEK"].ToString());
                    if (prodplanrate == 0
                           || wastageek == 0)
                    {
                        MessageBox.Show("请设置加成和采购损耗!");
                        return;
                    }*/
                    rek["EKPME1"] = Math.Round(Convert.ToDouble(vw["REQ"].ToString()) * (1 + prodplanrate * 0.01) * (1 + wastageek * 0.01), 2);
                    rek["EKPEFARBE"] = Math.Round(Convert.ToDouble(rek["EKPME1"].ToString()) / (1 + wastageek * 0.01), 2);
                    //rek["EKPEART"] = "0;" + (Math.Round(1 / (1 + wastageek * 0.01), 2)).ToString() + ";";
                    //string FGRLFD = vw["FGRLFD"].ToString();
                    //rek["EKPEART"] = "0;" + (Math.Round(1 / (1 + wastageek * 0.01), 2)).ToString() + ";" + prodplanrate * 0.01 + ";" + FGRLFD + ";";
                    rek["EKPEART"] = "0;" + (Math.Round(1 / (1 + wastageek * 0.01), 2)).ToString() + ";" + prodplanrate * 0.01 + ";0;";
                    tpEKPOS.Rows.Add(rek);
                }
                SetTmp.ICC_EKPOS.Clear();
                SetTmp.Merge(tpEKPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                DataRow[] rows;
                vwXDECK.View.MoveCurrentTo(-1);
                foreach (DataRow vw in temp.Rows)
                {
                    string ART = vw["ART"].ToString();
                    string VAR = vw["VAR"].ToString();
                    string FARBE = vw["COLOR"].ToString();
                    string SIZE = vw["ASIZE"].ToString();
                    string CREF = vw["CREF"].ToString();
                    string ABPART = vw["ABPART"].ToString();

                    rows = SetData.ICC_XDECK.Select("ART = '" + ART + "' AND VAR='" + VAR + "' AND COLOR='" + FARBE + "' AND ASIZE='" + SIZE
                        + "' AND CREF='" + CREF + "' AND ABPART='" + ABPART + "'");
                    foreach (DataRow rw in rows)
                    {
                        rw.Delete();
                    }
                }
                SetData.AcceptChanges();
                SetTmp.ICC_EKPOS.Clear();
                SetTmp.Merge(tpEKPOS);
                btnRefreshPurchase.IsEnabled = true;
                txtWastageEK.Text = "0";
                txtPlanRate.Text = "0";
                txtTmpEKME1.Text = "0";
            }
        }
        private void dlgITXDECK_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                pSType = "P";
                if (dwITXSTOCK != null)
                    pSType = "B";

                if (pSType == "P")
                {
                    m_Data.Reservation(dwITXXDECK, dwITXEKPOS, SetData, false, 1);
                }
                if (pSType == "B")
                {
                    m_Data.Reservation(dwITXXDECK, dwITXSTOCK, SetData, false, 1);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            zonePlan.IsExpanded = true;
            if (m_Prn == null)
            {
                m_Prn = new YCAEK03DOC();
                m_Prn.SetUp(dicParamater);
                m_Prn.PrnType = "OpenExcel";
            }
            string processed = "";
            foreach (DataRow row in Set4ITX.ICC_EKPOS.Rows)
            {
                string KRS = row["EKPAUFKRS"].ToString();
                string LFD = row["EKPAUFLFD"].ToString();
                if (processed.Contains(KRS + LFD + ";"))
                    continue;
                processed += KRS + LFD + ";";
                EventDispatcher.Instance.RaiseStatus("开始:" + KRS + LFD, StatusEventType.RunningProgress);
                m_Prn.KRS = KRS;
                m_Prn.LFD = LFD;
                m_Prn.btnQuery_Click(null, null);
                m_Prn.btnPrint_Click(null, null);
                EventDispatcher.Instance.RaiseStatus("完成:" + KRS + LFD, StatusEventType.StopProgress);
            }
            Set4ITX.Clear();
            btnPurchase.IsEnabled = true;
        }
        #endregion
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "ART LIKE '" + txtMAT.Text.ToString() 
                + "%' AND SELLER LIKE '%" + txtSELLER.Text.ToString() 
                + "%' AND ABPART LIKE '"+txtFART.Text.Trim()+"%' AND CREF LIKE '"+txtColorRef.Text.Trim()+"%'";
            //DataRow[] rows = SetData.ICC_XDECK.Select(filter);
            cvXDECK.CustomFilter = filter;
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            cvXDECK.CustomFilter = null;
        }
        private void cbSECTION_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            txtSection.Text += cb.SelectedValue + ";";
        }
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dwTMPEKPOS == null)
                return;
            if (dwLIEFDAT == null)
                return;
            dwTMPEKPOS["EKPLIEFNR"] = dwLIEFDAT["LSLIEFNR"];
            vwLIEFDAT.View.MoveCurrentTo(-1);
            //dwTMPEKPOS["EKPLIEFNR"]                
        }
        private void btnEKClear_Click(object sender, RoutedEventArgs e)
        {
            if (vwITXEKPOS.View != null)
            {
                vwITXEKPOS.View.MoveCurrentTo(-1);
            }
        }
    }
}